import {CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM, INITIAL_ITEM_ACTION} from './actionType';

const defaultState = {
    inputValue: '',
    list: []
};

// reducer can receive sate but it could not modify the state
export default (state = defaultState, action) => {
    if (action.type === CHANGE_INPUT_VALUE) {

        // copy the prev state deeply
        const newState = JSON.parse(JSON.stringify(state));
        newState.inputValue = action.value;

        // return to store
        return newState;
    }
    if (action.type === ADD_TODO_ITEM) {
        // [key]: the state is the previous state
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.push(newState.inputValue);
        newState.inputValue = '';
        return newState;
    }
    if (action.type === DELETE_TODO_ITEM) {
        // use 'splice' to remove elements from the array
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.splice(action.index, 1);
        return newState;
    }
    if (action.type === INITIAL_ITEM_ACTION) {
        const newState = JSON.parse(JSON.stringify(state));
        newState.list = action.value;
        return newState;
    }


    return state;
}